package com.hly.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.common.constant.ProductConstant;
import com.hly.common.utils.PageUtils;
import com.hly.common.utils.Query;
import com.hly.product.dao.AttrAttrgroupRelationDao;
import com.hly.product.dao.AttrDao;
import com.hly.product.dao.AttrGroupDao;
import com.hly.product.dao.CategoryDao;
import com.hly.product.entity.*;
import com.hly.product.service.AttrService;
import com.hly.product.service.CategoryService;
import com.hly.product.service.SkuSaleAttrValueService;
import com.hly.product.vo.AttrRespVo;
import com.hly.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                  new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取所有分类显示列表
     * @param params
     * @param cateLogId
     * @param type
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(HashMap<String, Object> params, Long cateLogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if( cateLogId != null && cateLogId != 0){
            wrapper.eq("catelog_id",cateLogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(i -> i.like("attr_id",key).or().like("attr_name",key));
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrRespVo> collect = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //拷贝类 将attrEntity属性值赋给attrRespVo
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(type)) {

                AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attr_id != null && attr_id.getAttrGroupId() != 0) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

                CategoryEntity byId = categoryDao.selectById(attrEntity.getCatelogId());
                if (byId != null && byId.getName() != null) {
                    attrRespVo.setCatelogName(byId.getName());
                }

            }

            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);

        return pageUtils;
    }

    /**
     * 保存属性
     * @param attrVo
     */
    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);
        //判断是否是基本属性，是的话在分组属性关联表添加关联
        if(attrVo.getAttrGroupId() != null && attrVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attrVo.getAttrGroupId());
            entity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(entity);
        }
    }

    /**
     * 根据attrId获取一个AttrRespVo ,并且填充分组id 分组name 分类路径
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(byId,attrRespVo);

        //设置属性分组 id name
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrRespVo.getAttrType()){
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
            if(attr_id != null){
                attrRespVo.setAttrGroupId(attr_id.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                if(attrGroupEntity != null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类name
        CategoryEntity categoryEntity = categoryDao.selectById(attrRespVo.getCatelogId());
        if (categoryEntity != null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        //设置分类路径
        Long[] path = categoryService.findCateLogPath(attrRespVo.getCatelogId());
        attrRespVo.setCatelogPath(path);
        return attrRespVo;
    }

    /**
     * 修改属性表、属性关联表
     * @param attrRespVo
     */
    @Transactional
    @Override
    public void updateAttr(AttrRespVo attrRespVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrRespVo,attrEntity);
        //修改属性表
        this.updateById(attrEntity);
        //判断是否是基本属性 ， 修改属性关联表
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrRespVo.getAttrType()){
            //通过attr_id判断是否存在关联
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(attrRespVo.getAttrId());
            entity.setAttrGroupId(attrRespVo.getAttrGroupId());
            if(count == 0){
                //不存在，新建
                attrAttrgroupRelationDao.insert(entity);
            }else{
                //存在，修改
                attrAttrgroupRelationDao.update(entity,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrRespVo.getAttrId()));
            }
        }
    }

    /**
     * 查询所有没有关联的属性
     * @param params
     * @return
     */
    @Override
    public PageUtils queryAssAttrPage(HashMap<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        List<Long> attrIdList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()).stream().map(attrAttrgroupRelationEntity -> attrAttrgroupRelationEntity.getAttrId()).collect(Collectors.toList());
        if(attrIdList.size() != 0){
            wrapper.notIn("attr_id",attrIdList);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        );
        String groupId = (String) params.get("groupId");
        if(groupId != null){
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
            List<AttrEntity> collect = page.getRecords().stream().filter(attrEntity -> attrEntity.getCatelogId().equals(attrGroupEntity.getCatelogId())).collect(Collectors.toList());
            page.setRecords(collect);
        }
        return new PageUtils(page);
    }

    /**
     * 根据attr_id删除基本属性，同时删除关联表中的数据
     * @param asList
     */
    @Transactional
    @Override
    public void removeAssByIds(List<Long> asList) {
        //基本属性，判断关联表中是否有数据
        if(attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id",asList)) !=0 ){
            //删除关联表中的数据
            attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id",asList));
        }
        this.removeByIds(asList);
    }

    /**
     * 根据attr_id删除销售属性，同时删除关联表中的数据
     * @param asList
     */
    @Override
    public void removeBusByIds(List<Long> asList) {
        //销售属性，判断关联表中是否有数据
        if(skuSaleAttrValueService.count(new QueryWrapper<SkuSaleAttrValueEntity>().in("attr_id",asList)) !=0 ){
            //删除关联表中的数据
            skuSaleAttrValueService.remove(new QueryWrapper<SkuSaleAttrValueEntity>().in("attr_id",asList));
        }
        this.removeByIds(asList);
    }

    /**
     * 返回集合里能被检索的规格属性 id
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return   this.listByIds(attrIds).stream().filter(attrEntity -> attrEntity.getSearchType() == 1).map(attrEntity -> attrEntity.getAttrId()).collect(Collectors.toList());
    }

    @Override
    public PageUtils listByCatelogId(Long catelogId, Map<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(catelogId != null){
            wrapper.and(i -> i.eq("attr_type",0).eq("catelog_id",catelogId));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrVo> attrVos = page.getRecords().stream().map(attrEntity -> {
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(attrEntity, attrVo);
            Long[] cateLogPath = categoryService.findCateLogPath(attrEntity.getCatelogId());
            for (Long categoryId : cateLogPath
            ) {
                CategoryEntity byId = categoryService.getById(categoryId);
                if (attrVo.getCatelogName() == null || attrVo.getCatelogName().equals("")) {
                    attrVo.setCatelogName(byId.getName());
                } else {
                    attrVo.setCatelogName(attrVo.getCatelogName() + "/" + byId.getName());
                }
            }
            List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (entities != null && entities.size() > 0) {
                AttrGroupEntity byId = attrGroupDao.selectById(entities.get(0).getAttrGroupId());
                attrVo.setGroupName(byId.getAttrGroupName());
            }
            return attrVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrVos);


        return pageUtils;
    }

}